<?php
header("Access-Control-Allow-Origin:*");

// 数据格式转化 (兼容旧系统)
function data_convert_config() {
    return array(
        'wm_tid' => '',
        'wm_stauts' => '',
        'wm_type' => 'YWLB',
        'wm_code' => array('IDNO', 'SR_NO'),
        'wm_carrier_id' => '',
        'wm_carrier' => '',
        'wm_vhc_code' => '',
        'wm_driver' => '',
        'wm_driver_tel' => '',
        'wm_dispatch_date' => '',
        'wm_dispatch_person' => '',
        'wm_dispatch_person_tel' => '',
        'wm_loading_place' => 'B_ADD',
        'wm_loading_date' => 'B_JH_DD',
        'wm_unloading_place' => 'E_ADD',
        'wm_ship' => 'SHIP_OVOY',
        'wm_voyage' => '',
        'wm_piece' => '',
        'wm_weight' => '',
        'wm_size' => '',
        'wm_note' => '',
        'wm_required_service_date' => '',
        'wm_check_interval' => '',
        'wm_version' => '',
        'wm_user' => '',
        'wm_accepted' => '',
        'wm_optid' => '',
        'wm_opdate' => '',
        'wm_cancel' => '',
        'wm_accepted_time' => '',
        'wm_cancel_time' => '',
        'wm_complete' => '',
        'wm_complete_time' => '',
        'wm_haul_id' => '',
        'wm_requiredl_note' => '',
        'wm_requiredl_note_voice' => '',
        'wm_handle_date' => '',
        'wm_isrun' => '',
        'wm_uuid' => '',
        'wm_awb_code' => 'TD_NO',
        'wm_fee' => '',
        'wm_isFee' => '',
        'wm_zmmtid' => '',
        'wm_startlng' => '',
        'wm_startlat' => '',
        'wm_transmit' => '',
        'wm_msg_arrive' => '',
        'wm_trailer' => '',
        'wm_ctnno' => '',
        'wm_qrcode' => '',
        'AMTN' => '',
    );
}

function data_convert($data) {
    $config = data_convert_config();

    foreach($config as $key => $val) {
        if($val) {
            if(is_array($val)) {
                foreach($val as $v) {
                    $data[$v] = $data[$key];
                }
            } else {
                $data[$val] = $data[$key];
            }
        }
    }
    return $data;
}

function key_convert($key) {
    $config = data_convert_config();
    return $config[$key];
}

function key_revert($key) {
    $config = data_convert_config();
    return array_search($key, $config);
}

function bindchannelId($pars){
	$status=0;
	$channelId=$pars->channelid?$pars->channelid:'';
	try{
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$a_member=&m("member");
		$a_member->edit($pars->uid,array('channelId'=>$channelId));
		$status=1;
		$waybill=&m('waybill');
		$bill=$waybill->find("ifnull(wm_accepted,0)=0  and ifnull(wm_stauts,'新建')='已派' and ifnull(wm_msg_arrive,'0')=0 and wm_user=".$pars->uid);
		if(empty($bill)===false){
			foreach($bill as $k=>$w){
				$wid=$w['wm_tid'];
				if($w['wm_type']=='疏港') {
					$sql="select * from zys_goods_trunk where exists(select 1 from zys_waybill_sub_trunk where g_tid=ws_gid and ws_wmtid=".$wid.")";
					$gt=$waybill->getRow($sql);
					pushMsg($channelId,
			'{"type":"3","result":{"wm_tid":"' . $wid . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_collectiontime']) . '到' . $gt['g_full_container_depot'] . '背重箱
			' . local_date('Y年m月d日 H点i分', $gt['g_packingtime']) . '送至' . $gt['g_loading_place'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
				}
				else if($w['wm_type']=='集港') {
					$sql="select * from zys_goods_trunk where exists(select 1 from zys_waybill_sub_trunk where g_tid=ws_gid and ws_wmtid=".$wid.")";
					$gt=$waybill->getRow($sql);
					pushMsg($channelId,
			'{"type":"3","result":{"wm_tid":"' . $wid . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_packingtime']) . '到' . $gt['g_loading_place'] . '装货
			' . local_date('Y年m月d日 H点i分', $gt['g_collectiontime']) . '前送至' . $gt['g_full_container_depot'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
				}
				else {
					$sql="select * from zys_goods_normal where exists(select 1 from zys_waybill_sub_normal where g_tid=ws_gid and ws_wmtid=".$wid.")";
					$gt=$waybill->getRow($sql);
					pushMsg($channelId,
			'{"type":"3","result":{"wm_tid":"' . $wid . '","type":"' . $gt['g_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_loading_date']) . '到' . $gt['g_loading_place'] . '提货
			' . local_date('Y年m月d日 H点i分', $gt['g_unloading_date']) . '送至' . $gt['g_unloading_place'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
				}
			}
		}
		$list='绑定成功' ;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

function pushMsg($channelId, $message, $msg_type)
{
	$sdk = new PushSDK();
	$channelId = $channelId ? $channelId : '3849309310203392735';
	try {
		// message content.
		//	$message = array (
		//	// 消息的标题.
		//	    'title' => 'Hi!',
		//	// 消息内容
		//	    'description' => "{'type':'01','info':'ddddddd'}"
		//	    );

		// 设置消息类型为 通知类型.
		$opts = array(
            'msg_type' => $msg_type ? $msg_type : 0
		);

		// 向目标设备发送一条消息
		$rs = $sdk->pushMsgToSingleDevice($channelId, $message, $opts);

		// 判断返回值,当发送失败时, $rs的结果为false, 可以通过getError来获得错误信息.
		if ($rs === false) {
			//print_r($sdk->getLastErrorCode());
			//	print_r($sdk->getLastErrorMsg());
		} else {
			// 将打印出消息的id,发送时间等相关信息.
			//print_r($rs);
		}
	} catch (Exception $ex) {

	}
}

function msg_arrive($pars){
	$status=0;
	$wid=$pars->tid?$pars->tid:0;
	try{
		$waybill=&m('waybill');
		$waybill->edit($wid,array('wm_msg_arrive'=>1));
		$list="成功";
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 获取认证信息
 * @param unknown_type $pars
 * @return string
 */
function getAuth($pars){
	$status=0;
	try{
		$db=&db();
		$uid=$pars->uid?$pars->uid:0;
		$type=$pars->a_type?$pars->a_type:0;
		if($type==0){
			$auth=&m('auth');
			$authRnt=$auth->getAuth($uid,$type);
		}elseif($type==2){
		 $auth=&m('authoperator');
		 $authRnt=$auth->getAuth($uid);
		}elseif($type==1){
			$sql="SELECT a_tid,a_userid,a_type,a_vhc_code,a_vhc_model,a_vhc_size,a_vhc_weight
,a_username,a_driver_licence,a_operator_code,a_apply_date,a_authed,a_auth_opid,a_auth_date,a_gpstype from zys_auth WHERE a_type=1 and a_userid=$uid
UNION 
select a.a_tid,c.a_userid,a.a_type,a.a_vhc_code,a.a_vhc_model,a.a_vhc_size,a.a_vhc_weight
,a.a_username,a.a_driver_licence,a.a_operator_code,c.a_apply_date,c.a_authed,c.a_auth_opid,c.a_auth_date,a.a_gpstype from zys_auth_car c
inner JOIN zys_auth a on c.a_tid=a.a_tid where c.a_userid=$uid";

			$authRnt=$db->getAll($sql);
		}
		$status=1;
	}catch (Exception $exp){
		$authRnt=$exp->getMessage();
	}
	return JSONResult($status,$authRnt,$pars);
}

function usecar($pars){
	$status=0;
	try{
		$db=&db();
		$uid=$pars->uid?$pars->uid:0;
		$code=$pars->code?$pars->code:0;

		$sql="SELECT a_tid,a_userid,a_type,a_vhc_code,a_vhc_model,a_vhc_size,a_vhc_weight
,a_username,a_driver_licence,a_operator_code,a_apply_date,a_authed,a_auth_opid,a_auth_date,a_gpstype,a_step from zys_auth WHERE a_type=1 and a_userid=$uid
and a_authed=1 and a_vhc_code='".$code."'
UNION All
select a.a_tid,c.a_userid,a.a_type,a.a_vhc_code,a.a_vhc_model,a.a_vhc_size,a.a_vhc_weight
,a.a_username,a.a_driver_licence,a.a_operator_code,c.a_apply_date,c.a_authed,c.a_auth_opid,c.a_auth_date,a.a_gpstype,a.a_step from zys_auth_car c
LEFT JOIN zys_auth a on c.a_tid=a.a_tid where c.a_userid=$uid and c.a_authed=1 and a_vhc_code='".$code."'";
			
		$authRnt=$db->getRow($sql);
		if(empty($authRnt)){
			throw new Exception("您还没有认证该车或认证还没有通过");
		}



		$sql="update zys_member set vhcCode='' where vhcCode='".$authRnt['a_vhc_code']."'";
		$db->query($sql);

		$sql="update zys_member set vhcCode='".$authRnt['a_vhc_code']."',type=1 where user_id=".$uid;
		$db->query($sql);

		$status=1;
	}catch (Exception $exp){
		$authRnt=$exp->getMessage();
	}
	return JSONResult($status,$authRnt,$pars);
}

function auth($pars){
	$status=0;
	try{
		$db=&db();

		$uid=$pars->uid?$pars->uid:0;
		$type=$pars->a_type?$pars->a_type:0;
		$auth=&m('auth');
		$authoperator=&m('authoperator');
		$authpic=&m("authpic");
		switch ($type){
			case 0:
				//实名认证
				$a_username=$pars->a_username?$pars->a_username:'';
				$a_driver_licence=$pars->a_driver_licence?$pars->a_driver_licence:'';
				$authInfo=array('a_username'=>$a_username,'a_driver_licence'=>$a_driver_licence);
				$rnt=$auth->autonymAuth($uid);
				break;
			case 1:
				//车辆认证

				$a_vhc_code=$pars->a_vhc_code?$pars->a_vhc_code:'';
				$a_vhc_model=$pars->a_vhc_model?$pars->a_vhc_model:'';
				$a_vhc_size=$pars->a_vhc_size?$pars->a_vhc_size:'';
				$a_vhc_weight=$pars->a_vhc_weight?$pars->a_vhc_weight:'';
				$authInfo=array('a_vhc_code'=>$a_vhc_code,'a_vhc_model'=>$a_vhc_model,
					'a_vhc_size'=>$a_vhc_size,'a_vhc_weight'=>$a_vhc_weight,'a_authed'=>0);

				break;
			case 2:
				//运营商认证
				$a_operator_code=$pars->a_operator_code?$pars->a_operator_code:'';
				$operator=&m('operator');
				$operatorId=$operator->getoperatorId($a_operator_code);
				if($operatorId<1){
					throw new Exception("输入运营商编码错误或不存在");
				}
				$authInfo=array('zao_operator_code'=>$a_operator_code,'zao_otid'=>$operatorId);
				$rnt=$authoperator->operatorAuth($uid,$a_operator_code);
				break;
		}
		if ($type == 0) {
			if (empty($rnt)) {
				$authInfo["a_apply_date"] = gmtime();
				$authInfo["a_type"] = $type;
				$authInfo["a_userid"] = $uid;
				$authid = $auth->add($authInfo);
				if ($authid > 0) {
					//TODO:保存图片
					$pics = $pars->pics;
					if (!empty($pics)) {
						foreach ($pics as $k => $v) {
							$authpic->add(array('ap_a_tid' => $authid, 'ap_key' => $v->key, 'ap_value' => $v->val));
						}
					}
					$status = 1;
					$rnt = '认证申请成功';
				}
			} else {
				if ($rnt['a_authed'] == 1)
				$rnt = '已认证';
				else {
					$auth->drop($rnt['a_tid']);
					$authpic->drop('ap_a_tid=' . $rnt['a_tid']);
					$authInfo["a_apply_date"] = gmtime();
					$authInfo["a_type"] = $type;
					$authInfo["a_userid"] = $uid;
					$authid = $auth->add($authInfo);
					if ($authid > 0) {
						//TODO:保存图片
						$pics = $pars->pics;
						if (!empty($pics)) {
							foreach ($pics as $k => $v) {
								$authpic->add(array('ap_a_tid' => $authid, 'ap_key' => $v->key, 'ap_value' => $v->val));
							}
						}
						$status = 1;
						$rnt = '认证申请成功';
					}
				}
			}
		}
		elseif($type == 1){
			$sql="select * from zys_auth where a_vhc_code='".$a_vhc_code."'";
			$at=$db->getRow($sql);
			if($at){
				if($at['a_userid']==$uid){
					if ($at['a_authed'] == 1)
					$rnt = '已认证';
					else {
						$auth->drop($at['a_tid']);
						$authpic->drop('ap_a_tid=' . $at['a_tid']);
						$authInfo["a_apply_date"] = gmtime();
						$authInfo["a_type"] = $type;
						$authInfo["a_userid"] = $uid;
						$authid = $auth->add($authInfo);
						if ($authid > 0) {
							//TODO:保存图片
							$pics = $pars->pics;
							if (!empty($pics)) {
								foreach ($pics as $k => $v) {
									$authpic->add(array('ap_a_tid' => $authid, 'ap_key' => $v->key, 'ap_value' => $v->val));
								}
							}
							$status = 1;
							$rnt = '认证申请成功';
						}
					}
				}else{
					if(!$at['a_authed']){
						$rnt = '车辆还没有通过审核';
					}else{
						$sql="select * from zys_auth_car where a_tid='".$at['a_tid']."' and a_userid='".$uid."'";
						$o=$db->getRow($sql);

						if($o&&$$o['a_authed'] == 1){
							$rnt = '已认证';
						}else{
							$sql="replace into zys_auth_car set a_tid='".$at['a_tid']."',a_userid='".$uid."',a_apply_date='".gmtime()."'";
							$db->query($sql);

							$status = 1;
							$rnt = '认证申请成功';
						}
					}
				}
			}else{
				$authInfo["a_apply_date"] = gmtime();
				$authInfo["a_type"] = $type;
				$authInfo["a_userid"] = $uid;
				$authid = $auth->add($authInfo);
				if ($authid > 0) {
					//TODO:保存图片
					$pics = $pars->pics;
					if (!empty($pics)) {
						foreach ($pics as $k => $v) {
							$authpic->add(array('ap_a_tid' => $authid, 'ap_key' => $v->key, 'ap_value' => $v->val));
						}
					}
					$status = 1;
					$rnt = '认证申请成功';
				}
			}
		}
		else {

			if (empty($rnt)) {
				$authInfo["zao_apply_date"] = gmtime();
				$authInfo["zao_usertid"] = $uid;
				$authid = $authoperator->add($authInfo);
				if ($authid > 0) {
					$status = 1;
					$rnt = '认证申请成功';
				} else
				$rnt = '认证申请失败';
			} else {
				if ($rnt['zao_authed'] == 1)
				$rnt = '已认证';
				else {
					$rnt = '认证申请已提交  等待审核';
				}
			}
		}
	}catch (Exception $exp){
		$rnt=$exp->getMessage();
	}
	return JSONResult($status,$rnt,$pars);
}


/**
 * 获取运单
 * @param unknown_type $pars
 */
function getwaybill($pars){
	//pushMSG();
	$status=0;
	try{
		$wmtid=$pars->wmtid?$pars->wmtid:0;
		$receive=$pars->receive?$pars->receive:0;
		$waybill=&m('waybill');
		$bill=$waybill->get("wm_tid=$wmtid");
		if(!empty($bill)){
			if($receive>0){
				$a_member=&m("member");
				$a_member->edit("user_id=".$pars->uid,array('current_waybill'=>$wmtid));
			}
			$bill['wm_loading_date']=local_date('Y-m-d H:i',$bill['wm_loading_date']);
			$bill['wm_required_service_date']=local_date('Y-m-d H:i',$bill['wm_required_service_date']);
			switch ($bill['wm_type']?$bill['wm_type']:'')
			{
				case WB_TTYPE_T_IN:
				case WB_TTYPE_T_OUT:
					//$trunk=$waybill->getRelatedData('has_trunk',$bill['wm_tid']);
					$trunk=$waybill->getAll('select * from zys_goods_trunk
		    		 inner join zys_waybill_sub_trunk on ws_gstid=g_tid 
		    		 inner join zys_goods_trunk_sub on ws_gstid=gs_tid  
		    		 where ws_wmtid='.$bill['wm_tid']);
					if(!empty($trunk))
					{
						foreach ($trunk as $k=>$v){
							$bill['trunk'][]=$v;
						}
					}
					break;
				default:
					//$normal=$waybill->getRelatedData('has_normal',$bill['wm_tid']);
					$extBill=$waybill->getRow('select * from zys_goods_normal where exists(select 1 from zys_waybill_sub_normal where g_tid=ws_gid and ws_wmtid='.$bill['wm_tid'].")");
					$bill['wm_loading_date']=local_date('Y-m-d H:i',$extBill['g_loading_date']);
					$bill['wm_unloading_date']=local_date('Y-m-d H:i',$extBill['g_unloading_date']);
					$bill['wm_loading_place']=$extBill['g_loading_place'];
					$bill['wm_unloading_place']=$extBill['g_unloading_place'];
					$bill['cartype']=$extBill['g_cartype'];
					$normal=$waybill->getAll('select * from zys_goods_normal_sub where exists(select 1 from zys_waybill_sub_normal where gs_tid=ws_gstid and ws_wmtid='.$bill['wm_tid'].")");
					if(!empty($normal))
					{
						foreach ($normal as $k=>$v){
							$bill['normal'][]=$v;
						}
					}
					break;
			}

			$haul=$waybill->getRelatedData('has_haul',$bill['wm_tid']);
			if(!empty($haul))
			{
				foreach ($haul as $k=>$v){
					$v['h_required_service_date']=local_date('Y-m-d H:i',$v['h_required_service_date']);
					$v['h_finished_date']=local_date('Y-m-d H:i',$v['h_finished_date']);
					$collect=$waybill->getAll('SELECT * FROM zys_haul_collect where hc_h_tid='.$v['h_tid']);
					if(!empty($collect)){
						foreach ($collect as $k_c=>$v_c){
							$v['h_collect_info'][]=$v_c;
						}
					}
					$bill['haul'][]=$v;
				}
			}
			//$monitor=$waybill->getRelatedData('has_monitor',$bill['wm_tid']);
			$monitor=$waybill->getALL('select * from zys_monitor inner join zys_monitor_main on m_zmmtid=zmm_tid where zmm_tid='.$bill['wm_zmmtid']);
			if(!empty($monitor))
			{
				foreach ($monitor as $k=>$v){
					$v['m_required_service_date']=local_date('Y-m-d H:i',$v['m_required_service_date']);
					$v['m_required_leave_date']=local_date('Y-m-d H:i',$v['m_required_leave_date']);
					$bill['monitor'][]=$v;
				}
			}

			//联系人
			$sql="select DISTINCT '派车人' as type ,wm_dispatch_person as name,wm_dispatch_person_tel as tel from zys_waybill_main where wm_tid=".$pars->wmtid." AND ifnull(wm_dispatch_person_tel,'')<>''
			      union ALL
			      select h_short_name as type,h_linkman as name,h_linkman_tel as tel from zys_haul where ifnull(h_short_name,'')<>'' and  h_wmtid=".$pars->wmtid ." AND ifnull(h_linkman_tel,'')<>''";
			$contacts=$waybill->getAll($sql);
			if(!empty($contacts)){
				foreach ($contacts as $k=>$v){
					$bill['contacts'][]=$v;
				}
			}
			//if($bill['wm_type']==='疏港'||$bill['wm_type']==='集港') {
			$goods=$waybill->getALL('select DISTINCT g_box,g_ctn_no from zys_goods_trunk_sub
										where EXISTS(select ws_gid from zys_waybill_sub_trunk where ws_wmtid='.$bill['wm_tid'].
										' and ws_gstid=gs_tid)');
			if(!empty($goods))
			{
				foreach ($goods as $k=>$v){
					$bill['CX']=(empty($bill['CX'])?"":$bill['CX']).$v['g_ctn_no'].'['.$v['g_box'].']|';
				}
			}
			//}
			else {
				$sql="SELECT '收货人' as type,g_consignee as name,g_consignee_tel as tel from zys_goods_normal inner join zys_waybill_sub_normal on ws_gid=g_tid where ws_tid=".$pars->wmtid." AND ifnull(g_consignee_tel,'')<>''
				union ALL
				SELECT '发货人' as type,g_consignor as name,g_consignor_tel as tel from zys_goods_normal inner join zys_waybill_sub_normal on ws_gid=g_tid where ws_tid=$pars->wmtid";
				$contacts=$waybill->getAll($sql);
				if(!empty($contacts)){
					foreach ($contacts as $k=>$v){
						$bill['contacts'][]=$v;
					}
				}
			}

			$ex=&m('exception');
			$Ex=$ex->find(array('conditions'=>'e_w_tid='.$wmtid));
			if(!empty($Ex))
			{
				foreach ($Ex as $k=>$v){
					$v['e_op_date']=local_date('Y-m-d H:i',$v['e_op_date']);
					//	$v['e_date']=local_date('Y-m-d H:i',$v['e_date']);
					$attr=$ex->getRelatedData('has_attr',$v['e_tid']);
					if(!empty($attr))
					{
						foreach ($attr as $ka=>$va){
							//$v['h_required_service_date']=local_date('Y-m-d H:i',$v['h_required_service_date']);
							$v['attr'][]=$va;
						}
					}
					$bill["exception"][]=$v;
				}
			}else{
				$bill["exception"]=array();
			}
			$bill["HDI"]=HAUL_DISTANCE_INTERVAL;
			$bill["HDL"]=HAUL_DISTANCE_LEVEL;
			$status=1;
		}else {
			$bill="获取运单失败";
		}


	}catch (Exception $exp){
		$bill=$exp->getMessage();
	}
	return JSONResult($status,$bill,$pars);
}
/**
 * 通讯录
 * Enter description here ...
 * @param unknown_type $pars
 * @throws Exception
 */
function addrbook($pars){
	$db =&db();
	$status=0;
	try{
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$wmtid=$pars->wmtid?$pars->wmtid:0;
		$sql="select DISTINCT type,name,tel from (
		select '派车人' as type ,wm_dispatch_person as name,wm_dispatch_person_tel as tel,wm_tid as id from zys_waybill_main
		union ALL
		select h_short_name as type,h_linkman as name,h_linkman_tel as tel,h_wmtid as id from zys_haul where ifnull(h_short_name,'')<>''
		union ALL
		select '收货人' as type,ws_consignee as name,ws_consignee_tel as tel,ws_wmtid as id from zys_waybill_sub_normal
		union ALL
		select '发货人' as type,ws_consignor as name,ws_consignor_tel as tel,ws_wmtid as id from zys_waybill_sub_normal
		) T
		where id=$pars->wmtid";
		$list=$db->getAll($sql);
		if(empty($list)){
			throw new Exception('人员不存在');
		}
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 * 未接单数据
 * Enter description here ...
 * @param unknown_type $pars
 * @throws Exception
 */
function unacceptinfo($pars)
{
	$status = 0;
	try {
		if (empty($pars->uid)) {
			throw new Exception('当前人员不存在');
		}
		$waybill =& m('waybill');
		$sql = 'select * from zys_waybill_main where wm_user=' . $pars->uid . ' and ifnull(wm_cancel,0)=0 and ifnull(wm_accepted,0)=0  order by wm_opdate asc ';
		$bill = $waybill->getRow($sql);
		if (!empty($bill)) {
			if (!empty($bill['wm_dispatch_date'])) {
				$bill['wm_dispatch_date'] = local_date('Y-m-d H:i', $bill['wm_dispatch_date']);
			}
			if (!empty($bill['wm_required_service_date'])) {
				$bill['wm_required_service_date'] = local_date('Y-m-d H:i', $bill['wm_required_service_date']);
			}

			if (!empty($bill['wm_loading_date'])) {
				$bill['wm_loading_date'] = local_date('Y-m-d H:i', $bill['wm_loading_date']);
			}
		}
		$sql = 'select wm_type,count(1) as num from zys_waybill_main where wm_user=' . $pars->uid
		. ' and ifnull(wm_cancel,0)=0 and ifnull(wm_accepted,0)=0 group by wm_type limit 0,2';
		$nums = $waybill->getAll($sql);
		if (!empty($nums)) {
			foreach ($nums as $k => $v) {
				$bill['total'][] = $v;
			}
		}
		$sql = 'select count(1) as num from zys_waybill_main where wm_user=' . $pars->uid
		. " and ifnull(wm_stauts,'新建')='已派' and ifnull(wm_accepted,0)=0 and ifnull(wm_cancel,0)=0 ";
		$nums = $waybill->getOne($sql);
		$bill['unaccept'] = $nums;
		$sql = "select count(1) as num from zys_waybill_main where wm_user=" . $pars->uid . ' and wm_complete=1 ';
		$nums = $waybill->getOne($sql);
		$bill['history'] = $nums;
		$status = 1;
	} catch (Exception $exp) {
		$bill = $exp->getMessage();
	}
	return JSONResult($status, $bill, $pars);
}
/**
 * 运单列表
 * Enter description here ...
 * @param unknown_type $pars
 * @throws Exception
 */
function waybilllist($pars)
{
	$status = 0;
	try {
		if (empty($pars->uid)) {
			//throw new Exception('当前人员不存在');
		}
		$row = $pars->row ? $pars->row : 0;
		$size = $pars->size ? $pars->size : 5;
		$accept = $pars->accept ? $pars->accept : 0;   //0 取消   1 已接单  2 历史 3 待接单 4 抢单
		$type = $pars->type ? $pars->type : '';
		
		$u="1=1";
		if(!empty($pars->uid)){
			$u.=" and wm_user=" . $pars->uid;
		}
		
		$waybill =& m('waybill');
		$list = array();
		
		$w=" 1=1 ";
		if($type){
			$w.=" and wm_type='集卡".$type."'";
		}
		if ($accept == 0) {             // 全部
			$sql = "select * from zys_waybill_main where ".$u." and ifnull(wm_cancel,0)!=1 and ((ifnull(wm_stauts,'新建')='已接单' and ifnull(wm_accepted,0)=1 and ifnull(wm_complete,0)=0 and ifnull(wm_isrun,0)=0) or (ifnull(wm_stauts,'新建')='已派' and ifnull(wm_accepted,0)=0 and ifnull(wm_cancel,0)=0)) order by wm_opdate desc limit " . $row . "," . $size;
		} else if ($accept == 2) {      // 已接 原状态 1
			$sql = "select * from zys_waybill_main where ".$u." and ifnull(wm_stauts,'新建')='已接单' and ifnull(wm_accepted,0)=1 and ifnull(wm_complete,0)=0 and ifnull(wm_isrun,0)=0 order by wm_opdate desc limit " . $row . "," . $size;
		} else if ($accept == 3) {      // 历史运单 原状态 2
			$sql = "select * from zys_waybill_main where ".$u." and (ifnull(wm_complete,0)=1 or ifnull(wm_isrun,0)=1) order by wm_opdate desc limit " . $row . "," . $size;
        } else if ($accept == 1) {      // 待接 原状态 3
			$sql = "select * from zys_waybill_main where ".$u." and ifnull(wm_stauts,'新建')='已派' and ifnull(wm_accepted,0)=0 and ifnull(wm_cancel,0)=0  order by wm_opdate desc limit " . $row . "," . $size;
		}else if ($accept == 4) {
			$sql = "select * from zys_waybill_main where $w and ifnull(wm_user,0)=0 and ifnull(wm_stauts,'新建')='已派' and ifnull(wm_accepted,0)=0 and ifnull(wm_cancel,0)=0  order by wm_opdate desc limit " . $row . "," . $size;
		}
		$bill = $waybill->getAll($sql);
		if (!empty($bill)) {
			foreach ($bill as $k => $v) {
				$v['wm_dispatch_date'] = local_date('Y-m-d H:i', $v['wm_dispatch_date']);
				$v['wm_loading_date'] = local_date('Y-m-d H:i', $v['wm_loading_date']);
				$v['wm_complete_time'] = local_date('Y-m-d H:i', $v['wm_complete_time']);
				$v['wm_required_service_date'] = local_date('Y-m-d H:i', $v['wm_required_service_date']);

				$goods=$waybill->getALL('select DISTINCT g_box,g_ctn_no from zys_goods_trunk_sub
			where EXISTS(select ws_gid from zys_waybill_sub_trunk where ws_wmtid='.$v['wm_tid'].
			' and ws_gstid=gs_tid)');
				if(!empty($goods))
				{
					foreach ($goods as $k=>$vv){
						$v['CX']=(empty($v['CX'])?"":$v['CX']).$vv['g_ctn_no'].'['.$vv['g_box'].']|';
					}
				}
				$list[] = data_convert($v);
			}
		}
		$status = 1;
	} catch (Exception $exp) {
		$list = $exp->getMessage();
	}
	return JSONResult($status, $list, $pars);
}

/**
 * 异常提报
 * @param unknown_type $pars
 * @return string
 */
function exceptionsubmit($file, $filelist, $pars)
{
	$status = 0;
	try {
		$code = $pars->code ? $pars->code : '';
		$type = $pars->type ? $pars->type : '';
		$content = $pars->content ? $pars->content : '';
		$hid = $pars->h_id ? $pars->h_id : 0;
		$wid = $pars->w_id ? $pars->w_id : 0;
		if (!empty($file)) {
			$voice_note = fileuploadAudio($file, 'data/ex_audio', 'zys_', $pars->uid, false);
		} else {
			$voice_note = $pars->voice ? $pars->voice : '';
		}
		if (empty($filelist)) {
			$pics = $pars->pics;
		} else {
			$pic2 = array();
			foreach ($filelist as $f) {
				if ($f) {
					$picname = fileupload($f, 'data/ex_pic', 'zys_', $pars->uid, false);
					if (!empty($picname)) {
						$pic2[] = $picname;
					}
				}
			}
		}
		$text_note = $pars->note ? $pars->note : '';
		$exInfo = array('e_op_tid' => $pars->uid,
            'e_op_date' => gmtime(),
            'e_bill_code' => $code,
            'e_type' => $type,
            'e_content' => $content,
            'e_voice_note' => $voice_note,
            'e_text_note' => $text_note,
            'e_h_tid' => $hid,
            'e_w_tid' => $wid,
            'e_staus' => '提报');
		$location = $pars->location;
		if (!empty($location)) {
			$exInfo['e_address'] = $location->address;
			//$exInfo['e_date']=$location->date;
			$exInfo['e_date'] = local_strtotime($location->date);
			$exInfo['e_lng'] = $location->lng;
			$exInfo['e_lat'] = $location->lat;
		}
		$ex =& m('exception');
		$exid = $ex->add($exInfo);
		if ($exid > 0) {
			//TODO:保存图片
			if (!empty($pics)) {
				$expic =& m("exattr");
				foreach ($pics as $k => $v) {
					$expic->add(array('ea_e_tid' => $exid, 'ea_type' => 0, 'ea_content' => $v->ea_content));
				}
				foreach ($pic2 as $v) {
					$expic->add(array('ea_e_tid' => $exid, 'ea_type' => 0, 'ea_content' => $v));
				}
			} else if (!empty($pic2)) {
				$expic =& m("exattr");
				foreach ($pic2 as $v) {
					$expic->add(array('ea_e_tid' => $exid, 'ea_type' => 0, 'ea_content' => $v));
				}
			}
			if ($hid > 0) {
				//$rnt=updateHaul($hid, -1, $exInfo['e_lng'], $exInfo['e_lat'],0, null, $pars->uid,null);
			}
			//			else if($wid>0){
			//				$waybill=&m('waybill');
			//				$data=array('wm_complete'=>1,'wm_complete_time'=>gmtime(),'wm_stauts'=>'异常');
			//				$waybill->edit('wm_tid='.$wid,$data);
			//			}
			else
			$rnt = '异常提报成功';
			$status = 1;
		}
	} catch (Exception $exp) {
		$rnt = $exp->getMessage();
	}
	return JSONResult($status, $rnt, $pars);
}
/**
 * 异常列表
 * @param unknown_type $pars
 * @return string
 */
function exceptionlist($pars){
	$status=0;
	$list=array();
	try{
		$row=$pars->row?$pars->row:0;
		$size=$pars->size?$pars->size:5;
		$wmtid=$pars->wmtid?$pars->wmtid:0;
		$haulid=$pars->haulid?$pars->haulid:0;
		$ex=&m('exception');
		if($wmtid>0){
			if($haulid>0){
				$Ex=$ex->getAll('select * from zys_exception left join zys_haul on e_h_tid =h_tid where e_op_tid='.$pars->uid.' and e_w_tid='.$wmtid.' and e_h_tid='.$haulid.' order by e_op_date desc ');
				//find(array('conditions'=>'e_op_tid='.$pars->uid.' and e_w_tid='.$wmtid.' and e_h_tid='.$haulid));
			}else{
				$Ex=$ex->getAll('select * from zys_exception left join zys_haul on e_h_tid =h_tid where e_op_tid='.$pars->uid.' and e_w_tid='.$wmtid.' order by e_op_date desc ');
				//find(array('conditions'=>'e_op_tid='.$pars->uid.' and e_w_tid='.$wmtid));
			}
		}else{
			//
			$Ex=$ex->getAll('select * from zys_exception left join zys_haul on e_h_tid =h_tid where e_op_tid='.$pars->uid.' order by e_op_date desc limit '.$row.','.$size);
			//find(array('conditions'=>'e_op_tid='.$pars->uid,'limit'=>$row.','.$size));
		}
		if(!empty($Ex))
		{
			foreach ($Ex as $k=>$v){
				$v['e_op_date']=local_date('Y-m-d H:i',$v['e_op_date']);
				//	$v['e_date']=local_date('Y-m-d H:i',$v['e_date']);
				$attr=$ex->getRelatedData('has_attr',$v['e_tid']);
				if(!empty($attr))
				{
					foreach ($attr as $ka=>$va){
						//$v['h_required_service_date']=local_date('Y-m-d H:i',$v['h_required_service_date']);
						$v['attr'][]=$va;
					}
				}
				$list[]=$v;
			}
		}
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


function ysplan($pars){
    $db =& db();
    $status=0;
    try{
        $IDNO = $pars->IDNO ? $pars->IDNO : '';

        $waybill_mod =& m('waybill');
        $a_member =& m("member");

        $waybillinfo = $waybill_mod->get("wm_code='$IDNO'");
        $tid = $waybillinfo['wm_tid'];
        if (!$IDNO || empty($waybillinfo)) {
            throw new Exception("运单不存在");
        }

        if($waybillinfo['wm_stauts']!='已派'){
            throw new Exception("运单不能接单");
        }

        $sql = "select 1 from zys_waybill_main where wm_user=" . $pars->uid." and wm_stauts='已接单'";
        $h = $db->getOne($sql);
        if ($h) {
            throw new Exception('您有未完成的运单不能接单 ERROR:order');
        }

        $usr = $a_member->get('user_id=' . $pars->uid);
        if (!empty($usr['current_waybill'])) {
            throw new Exception('您有未完成的运单不能接单 ERROR: user');
        }

        $data = array(
            'wm_accepted' => 1,
            'wm_accepted_time' => gmtime(),
            'wm_stauts' => '已接单',
            'wm_user' => $pars->uid,
            'wm_driver' => $usr['user_name'],
            'wm_driver_tel' => $usr['phone_tel'],
            'wm_vhc_code' => $usr['vhcCode']
        );

        if (checkUrl(SOAP_URL)) {
            $client = new SoapClient(SOAP_URL);

            $sql = "select wm_code from zys_waybill_main where wm_tid=" . $tid;
            $code = $db->getOne($sql);
            if ($code) {
                $param = array();
                $param['Code'] = $code;
                $param['status'] = 5;

                $response = $client->__soapCall("str", array($param));
                $response = json_decode($response->strResult, true);
            }
        }

        $waybill_mod->edit($tid, $data);
        $sql = 'select count(*) as num from zys_waybill_main where wm_user=' . $pars->uid
            . " and ifnull(wm_stauts,'新建')='已派' and ifnull(wm_accepted,0)=0 ";
        $nums = $waybill_mod->getOne($sql);

        $list = $waybill_mod->get($tid);
        $list['wm_dispatch_date'] = local_date('Y-m-d H:i', $list['wm_dispatch_date']);
        $list['wm_loading_date'] = local_date('Y-m-d H:i', $list['wm_loading_date']);
        $list['wm_required_service_date'] = local_date('Y-m-d H:i', $list['wm_required_service_date']);
        $list['unaccept'] = empty($nums) ? 0 : $nums;
        $status = 1;
    } catch (Exception $exp) {
        $list = $exp->getMessage();
    }
    return JSONResult($status, $list, $pars);
}

/**
 * 运单提交
 * Enter description here ...
 * @param unknown_type $pars  $type 0 取消运单  1接收运单 2开始运单  3 完成    4 接收并开始
 * @throws Exception
 */
function waybillsubmit($pars)
{
	$status = 0;
	try {
		$tid = $pars->tid ? $pars->tid : 0;
		$type = $pars->type ? $pars->type : 0;
		$gps = $pars->gps;
		$lat = $pars->lat ? $pars->lat : 0;
		$lng = $pars->lng ? $pars->lng : 0;
		$waybill_mod =& m('waybill');
		$a_member =& m("member");

		$waybillinfo = $waybill_mod->get($tid);
		if (empty($waybillinfo)) {
			throw new Exception("运单不存在");
		}

		$db =& db();
		//取消运单
		if ($type == 0) {
			if($waybillinfo['wm_stauts']!='已派'){
				throw new Exception("运单不能取消");
			}

			$data = array('wm_cancel' => 1, 'wm_cancel_time' => gmtime(), 'wm_stauts' => '已取消');
			$a_member->edit('user_id=' . $pars->uid . ' and current_waybill=' . $tid, array('current_waybill' => 0));

			if (checkUrl(SOAP_URL)) {
			 $client = new SoapClient(SOAP_URL);

			 $sql = "select wm_code from zys_waybill_main where wm_tid=" . $tid;
			 $code = $db->getOne($sql);
			 if ($code) {
			 	$param = array();
			 	$param['Code'] = $code;
			 	$param['status'] = 4;

			 	$response = $client->__soapCall("str", array($param));
			 	$response = json_decode($response->strResult, true);
			 }
			}
		} else if ($type == 1) { //接收运单
			if($waybillinfo['wm_stauts']!='已派'){
				throw new Exception("运单不能接单");
			}

			$sql = "select 1 from zys_waybill_main where wm_user=" . $pars->uid." and wm_stauts='已接单'";
			$h = $db->getOne($sql);
			if ($h) {
				throw new Exception('您有未完成的运单不能接单');
			}

			$usr = $a_member->get('user_id=' . $pars->uid);
			if (!empty($usr['current_waybill'])) {
				throw new Exception('您有未完成的运单不能接单');
			}

			if(empty($waybillinfo['wm_user'])||empty($waybillinfo['wm_vhc_code'])){
				if (checkUrl(SOAP_URL)) {
					$client = new SoapClient(SOAP_URL);
	
					$param = array();
					$param['Code'] = $waybillinfo['wm_code'];
					$param['CarNo'] = $usr['vhcCode'];
					$param['Driver'] = $usr['user_name'];
					$param['Tel'] = $usr['phone_tel'];
					$response = $client->__soapCall("ReturnCarNo", array($param));
					$response = json_decode($response->ReturnCarNoResult, true);
					
					if($response){
						throw new Exception('抢单失败');
					}
				}else{
					throw new Exception('抢单失败');
				}
			}
			
			$data = array('wm_accepted' => 1, 'wm_accepted_time' => gmtime(), 'wm_stauts' => '已接单',
			'wm_user' => $pars->uid,'wm_driver' => $usr['user_name'],'wm_driver_tel' => $usr['phone_tel'],'wm_vhc_code' => $usr['vhcCode']);

			if (checkUrl(SOAP_URL)) {
				$client = new SoapClient(SOAP_URL);

				$db =& db();
				$sql = "select wm_code from zys_waybill_main where wm_tid=" . $tid;
				$code = $db->getOne($sql);
				if ($code) {
					$param = array();
					$param['Code'] = $code;
					$param['status'] = 5;

					$response = $client->__soapCall("str", array($param));
					$response = json_decode($response->strResult, true);
				}
			}
		} else if ($type == 2) //开始运输
		{
			if($waybillinfo['wm_stauts']!='已接单'){
				throw new Exception("运单不能开始运输");
			}

			$usr = $a_member->get('user_id=' . $pars->uid . ' and current_waybill=' . $tid);
			if (!empty($usr)) {
				throw new Exception('当前用户已开始运程不能执行新运单');
			}
			$data = array('wm_handle_date' => gmtime(), 'wm_isrun' => 1, 'wm_stauts' => '执行中', 'wm_startlng' => $lng, 'wm_startlat' => $lat);
			$a_member->edit($pars->uid, array('current_waybill' => $tid));
			$haul =& m('haul');
			$haul_info = $haul->getRow('select * from zys_haul  where h_wmtid=' . $tid . ' and ifnull(h_finished,0)=0 ORDER BY h_order asc LIMIT 0,1');

            // 添加 gps 记录
            gps_record($waybillinfo['wm_vhc_code'], $lat, $lng, (float)$gps->speed, $waybillinfo['wm_tid']);

			if (empty($haul_info) === false) {
				$haul->edit($haul_info['h_tid'], array('h_finished' => 1));
				$data['wm_haul_id'] = $haul_info['h_tid'];
			}

			if (checkUrl(SOAP_URL)) {
			 $client = new SoapClient(SOAP_URL);

			 $db =& db();
			 $sql = "select wm_code from zys_waybill_main where wm_tid=" . $tid;
			 $code = $db->getOne($sql);
			 if ($code) {
			 	$param = array();
			 	$param['Code'] = $code;
			 	$param['status'] = 6;

			 	$response = $client->__soapCall("str", array($param));
			 	$response = json_decode($response->strResult, true);
			 }
			 //fwrite($file,'option:start code:'.$code.' status:5'.' result:'.$response);
			}
		} else if ($type == 3) //运单完成
		{
			if($waybillinfo['wm_stauts']!='执行中'){
				throw new Exception("运单不能完成");
			}

			$haul =& m('haul');
			$haulinfo = $haul->get('h_wmtid=' . $tid . ' and (ifnull(h_finished,0)<>2 and ifnull(h_finished,0)<>-1) ');
			if(!empty($haulinfo)){
				throw new Exception('当前运单有未完成运程不能完成');
			}
			$data=array('wm_complete'=>1,'wm_complete_time'=>gmtime(),'wm_stauts'=>'已完成','wm_endlng'=>$lng,'wm_endlat'=>$lat);
//			$data = array('wm_complete' => 1, 'wm_complete_time' => gmtime(), 'wm_stauts' => '已完成');
			$a_member->edit($pars->uid, array('current_waybill' => 0));

            // 添加 gps 记录
            gps_record($waybillinfo['wm_vhc_code'], $lat, $lng, (float)$gps->speed, $waybillinfo['wm_tid']);

			ini_set('default_socket_timeout', 15);
			if (checkUrl(SOAP_URL)) {
				$client = new SoapClient(SOAP_URL);

				$db =& db();
				$sql = "select wm_code from zys_waybill_main where wm_tid=" . $tid;
				$code = $db->getOne($sql);
				if ($code) {
					$param = array();
					$param['Code'] = $code;
					$param['status'] = 2;

					$response = $client->__soapCall("str", array($param));
					$response = json_decode($response->strResult, true);
				}
			}

		}
		//更新

		/*if (checkUrl(SOAP_URL)) {
			$client = new SoapClient(SOAP_URL);
			$clientexecute = false;
			if ($waybillinfo['wm_code']) {
			$param = array();
			$param['Code'] = $waybillinfo['wm_code'];
			if ($type == 0) { //取消运单
			$param['status'] = 4;
			} else if ($type == 1) { //接收运单
			$param['status'] = 5;
			} else if ($type == 2) //开始运输
			{
			$param['status'] = 6;
			} else if ($type == 3) //运单完成
			{
			$param['status'] = 2;
			}
			if ($waybillinfo['wm_type'] == "疏港" || $waybillinfo['wm_type'] == "集港") {
			$waybilltrunk_mod =& m("waybilltrunk");
			$goodstrunk_mod =& m('goodstrunk');
			$waybilltrunklists = $waybilltrunk_mod->find(array(
			"conditions" => "ws_wmtid=$tid",
			"fields" => "ws_gid",
			));
			$waybilltrunk_ids = "0";
			foreach ($waybilltrunklists as $key => $val) {
			$waybilltrunk_ids .= ',' . $val['ws_gid'];
			}
			if ($waybilltrunk_ids) {
			$goodstrunklists = $goodstrunk_mod->find(array(
			"conditions" => "ifnull(g_source,'')!='' and g_tid in($waybilltrunk_ids)",
			"fields" => "g_source",
			));
			if ($goodstrunklists) {
			foreach ($goodstrunklists as $key => $val) {
			$param['tcode'] = $val['g_source'];
			$param['CarNo'] = $waybillinfo['wm_vhc_code'];
			$response = $client->__soapCall("str", array($param));
			$response = json_decode($response->strResult, true);
			$clientexecute = true;
			}
			}
			}
			}
			if (!$clientexecute) {
			$response = $client->__soapCall("str", array($param));
			$response = json_decode($response->strResult, true);
			}
			}
			}*/

		$waybill_mod->edit($tid, $data);
		//		$sql='select count(1) as num from zys_waybill_main where wm_user='.$pars->uid
		//		.' and ifnull(wm_cancel,0)=0 and ifnull(wm_complete,0)=0 and ifnull(wm_accepted,0)=1 and ifnull(wm_isrun,0)=0';
		$sql = 'select count(1) as num from zys_waybill_main where wm_user=' . $pars->uid
		. " and ifnull(wm_stauts,'新建')='已派' and ifnull(wm_accepted,0)=0 ";
		$nums = $waybill_mod->getOne($sql);
		if ($type == 1 || $type == 2) {
			$list = $waybill_mod->get($tid);
			$list['wm_dispatch_date'] = local_date('Y-m-d H:i', $list['wm_dispatch_date']);
			$list['wm_loading_date'] = local_date('Y-m-d H:i', $list['wm_loading_date']);
			$list['wm_required_service_date'] = local_date('Y-m-d H:i', $list['wm_required_service_date']);
		} else {
			$list = array();
		}
		if ($type == 3)
		$list['wm_tid'] = -1;
		$list['unaccept'] = empty($nums) ? 0 : $nums;
		$status = 1;
	} catch (Exception $exp) {
		$list = $exp->getMessage();
	}
	return JSONResult($status, $list, $pars);
}

/**
 * 写入 GPS 信息
 */
function gps_record($gps_carno, $gps_latitude, $gps_longitude, $gps_speed, $wm_tid) {
    $model = m('gps');
    $model->add(array(
        'gps_vehicleno' => $gps_vehicleno,
        'gps_carno'     => $gps_carno,
        'gps_latitude'  => $gps_latitude,
        'gps_longitude' => $gps_longitude,
        'gps_speed'     => $gps_speed,
        'gps_gpstime'   => date('Y-m-d H:i:s'),
        'gps_addtime'   => date('Y-m-d H:i:s'),
        'gps_wmtid'     => $wm_tid,
    ));
}

/**
 * 运程 GPS 记录
 */
function waybillgps($pars) {
    $gps = $pars->gps;
    $tid = (int)$pars->tid;

    $waybill_mod =& m('waybill');
    $waybillinfo = $waybill_mod->get($tid);
    // 添加 gps 记录
    gps_record($waybillinfo['wm_vhc_code'], (float)$gps->lat, (float)$gps->lng, (float)$gps->speed, $waybillinfo['wm_tid']);

    // 更新运程
    $data = array('wm_handle_date' => gmtime());
    $waybill_mod->edit($tid, $data);
    return JSONResult(1, array(), $pars);
}

/**
 * 累计接单数量
 * Enter description here ...
 * @param unknown_type $pars
 */
function waybillnum($pars){
	$status=0;
	$list=array();
	try{
		$type=$pars->type?$pars->type:0;
		switch ($type){
			case 0:  //累计接单数量
				$sql='select count(1) as num from zys_waybill_main where wm_user='.$pars->uid
				.' and ifnull(wm_accepted,0)=1 ';
				break;
			case 1:  //待接单数量
				$sql='select count(1) as num from zys_waybill_main where wm_user='.$pars->uid
				." and ifnull(wm_accepted,0)=0 and ifnull(wm_stauts,'新建')='已派' ";
		}
		$waybill=&m('waybill');

		$nums=$waybill->getOne($sql);
		$nums=$nums?$nums:0;
		$list['num']=$nums;
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 * 运程确认
 * @param unknown_type $pars
 * @throws Exception
 * @return string
 */
function haulSubmit($pars, $files)
{
	$status = 0;
	try {
		$tid = $pars->tid ? $pars->tid : 0;
		$lat = $pars->lat ? $pars->lat : 0;
		$lng = $pars->lng ? $pars->lng : 0;
		$date = $pars->date ? local_strtotime($pars->date) : 0;
		$c = empty($pars->c) ? 0 : 1;

		$haul =& m('haul');
		$haulinfo = $haul->get('h_tid=' . $tid);
		if (!empty($haulinfo)) {
			//			if($haulinfo['h_finished']==2){
			//						throw new Exception('当前运程已确认');
			//					}
			$lat = $pars->lat ? $pars->lat : 0;
			$lng = $pars->lng ? $pars->lng : 0;
			$attr = $pars->attr;
			$rnt = updateHaul($tid, 2, $lat, $lng, $date, $attr, $pars->uid, $c, $files);
			$status = 1;
		} else {
			throw new Exception('当前运程不存在');
		}
	} catch (Exception $exp) {
		$rnt = $exp->getMessage();
	}
	return JSONResult($status, $rnt, $pars);
}

/**
 * 运程确认
 * @param unknown_type $pars
 * @throws Exception
 * @return string
 */
function updateHaul($tid,$status,$lat,$lng,$attr,$uid,$files){
	$haulinfo=array(
		'h_finished'=>$status,
		'h_finished_date'=>gmtime(),
		'h_finished_lng'=>$lng,
		'h_finished_lat'=>$lat,
		'h_finished_pid'=>$uid);
	$haul=&m('haul');
	$haul->edit('h_tid='.$tid,$haulinfo);
	$haulinfo=$haul->get($tid);
	if(!empty($attr)&&!empty($haulinfo)){
		$haul_c=&m("haulcollect");
		foreach($attr as $k=>$v){
			$val='';
			$hc_tid=$v->tid?$v->tid:0;
			$haul_c_info=$haul_c->get($hc_tid);
			if(empty($haul_c_info)===false){
				switch ($haul_c_info['h_collect_type']){
					case 3:
						$num=$v->num?$v->num:0;
						$filelist=array();
						for($i=0;$i<$num;$i++){
							$f=$files['image_'.$hc_tid.'_'.$i]?$files['image_'.$hc_tid.'_'.$i]:'';
							$filelist[]=$f;
						}
						if(empty($filelist)===false){
							foreach($filelist as $fv){
								$val=$val.fileupload($fv,'data/haul_pic','zys_',$uid,false);
								$val=$val.",";
							}
						}
						else
						$val=$v->val;
						break;
					case 4:
						$f=$files['voice_'.$hc_tid]?$files['voice_'.$hc_tid]:'';
						if(empty($f)===false){
							$val=$val.fileuploadAudio($f,'data/haul_audio','zys_',$uid,false);
						}
						else
					 $val=$v->val;
					 	
					 break;
					default:
						$val=$v->val;
						break;
				}
				//回写数据
				if(empty($haul_c_info['h_callback_column'])===false){
					list($table, $col, $pk) =split('\|',$haul_c_info['h_callback_column']);
					$pk2 =str_replace('@wmtid',$haulinfo['h_wmtid'],str_replace('@htid',$tid,$pk));
					$sql='update '.$table.' set '.$col."='".$val."' where ".$pk2;
					$haul->query($sql);
				}
			}
			$haul_c->edit('hc_tid='.$hc_tid,array('h_collect_val'=>$val));
		}
	}

	$waybill=&m('waybill');
	$sql='select ifnull(wm_user,0) as wm_user,wm_type,wm_vhc_code,wm_driver,wm_loading_place,wm_unloading_place,gs.g_box,g_outkey,g_itm,wm_code from zys_waybill_main m
			left join zys_waybill_sub_trunk s on m.wm_tid=s.ws_wmtid 
			left join zys_goods_trunk_sub gs on gs.gs_tid=s.ws_gstid
			where wm_tid='.$haulinfo['h_wmtid']." limit 1";
	$bill=$waybill->getRow($sql);


	$haul_info=$haul->getRow('select * from zys_haul m where exists(select h_wmtid from zys_haul h where h_tid='.$tid
	.' and h.h_wmtid=m.h_wmtid and m.h_order>h.h_order) and ( ifnull(h_finished,0)=0 or ifnull(h_finished,0)=1)');
	if(empty($haul_info)===false){
		$haul->edit($haul_info['h_tid'],array('h_finished'=>1));
		$waybill=&m('waybill');
		$waybill->edit($haul_info['h_wmtid'],array('wm_haul_id'=>$haul_info['h_tid']));
	}
	$rnt=$haul->get('h_tid='.$tid);
	if(empty($rnt)===false){
		$rnt['h_finished_date']=local_date('Y-m-d H:i',$rnt['h_finished_date']);
		$rnt['next_id']=empty($haul_info['h_tid'])?0:$haul_info['h_tid'];
	}
	return $rnt;
}

/**
 *
 * 运程测距
 * @param unknown_type $pars
 * @return string
 */
function distance($pars){
	$status=0;
	try{
		$wm_tid=$pars->wm_tid?$pars->wm_tid:0;
		$h_tid=$pars->h_tid?$pars->h_tid:0;
		$distance=$pars->distance?$pars->distance:0;
		$duration=$pars->duration?$pars->duration:0;
		$haul=&m('haul');
		$haul->edit($h_tid,array('h_distance'=>$distance,'h_distancetime'=>$duration));
		$status=1;
		$rnt='提交成功';
	}
	catch (Exception $exp){
		$rnt=$exp->getMessage();
	}
	return JSONResult($status,$rnt,$pars);
}

/**
 *
 * 距下一运程距离
 * @param unknown_type $pars
 * @return string
 */
function frontdistance($pars){
	$status=0;
	try{
		$wm_tid=$pars->wm_tid?$pars->wm_tid:0;
		$h_tid=$pars->h_tid?$pars->h_tid:0;
		$distance=$pars->distance?$pars->distance:0;
		$duration=$pars->duration?$pars->duration:0;
		$haul=&m('haul');
		$haul->edit($h_tid,array('h_frontdistance'=>$distance,'h_frontdistancetime'=>$duration));
		$status=1;
		$rnt='提交成功';
	}
	catch (Exception $exp){
		$rnt=$exp->getMessage();
	}
	return JSONResult($status,$rnt,$pars);
}


/**
 * 创建疏港运单
 * $B_JH_DD --计划开始时间
 ,E_JH_DD  --计划结束时间
 , B_ADD   --起运地
 ,E_ADD   --目的地
 ,'疏港' YWLB   --业务类别
 ,CX  --箱型尺寸
 ,QTY   --箱量
 ,SHIP_OVOY   --船次
 ,TD_NO    --提单号
 ,SR_NO   --计划号
 ,ITM   --计划序号
 ,PG_ZT   --运输状态
 */
function createSGWayBill($pars){

	//制单人
	$optid=1;
	$opDate=gmtime();
	//承运人
	$carrier_id=12;
	$carrier="全球捷运";

	$status=0;
	$IDNO=$pars->IDNO?$pars->IDNO:'';

	try  {
		if(empty($IDNO)){
			throw new Exception("运单号不存在");
		}
		$waybill=&m('waybill');
        $bill = $waybill->get("wm_code='$IDNO'");
        $bill_id = $bill['wm_tid'];
		if(!$bill)
		{
			throw new Exception("运单不存在");
		}
        $pars->tid = $bill_id;
        $pars->type = 2;
        $pars->lat = $pars->gps ? $pars->gps->lat : 0;
        $pars->lng = $pars->gps ? $pars->gps->lng : 0;

        waybillsubmit($pars);

        $rnt = $waybill->get($bill_id);
        $status = 1;
	}
	catch (Exception $exp){
		$rnt=$exp->getMessage();
	}
	return JSONResult($status,$rnt,$pars);
}

function createJGWayBill($pars){
	//制单人
	$optid=1;
	$opDate=gmtime();
	//承运人
	$carrier_id=12;
	$carrier="全球捷运";

	$status=0;
	$bill_id=-1;
	$YWLB=$pars->YWLB?$pars->YWLB:'集港';
	$IDNO=$pars->IDNO?$pars->IDNO:'';
	$vhcCode=$pars->vhc?$pars->vhc:"";  //車牌号
	$B_JH_DD=$pars->B_JH_DD?$pars->B_JH_DD:'';
	$E_JH_DD=$pars->E_JH_DD?$pars->E_JH_DD:'';
	$B_ADD=$pars->B_ADD?$pars->B_ADD:'';
	$E_ADD=$pars->E_ADD?$pars->E_ADD:'';
	$BOX_NO =$pars->BOX?$pars->BOX:"";

	$CX =$pars->CX?$pars->CX:'' ;
	$QTY =1;
	$SHIP =$pars->SHIP_OVOY?$pars->SHIP_OVOY:'';
	$TD_NO =$pars->TD_NO?$pars->TD_NO:'';
	$SR_NO =$pars->SR_NO?$pars->SR_NO:'';
	$ITM =$pars->ITM?$pars->ITM:0;

	$wm_trailer=$pars->gvhc?$pars->gvhc:""; //挂车号
	$LINK=$pars->LINK?$pars->LINK:'';
	$TEL=$pars->TEL?$pars->TEL:'';
	$B_LINK=$pars->B_LINK?$pars->B_LINK:'';
	$B_TEL=$pars->B_TEL?$pars->B_TEL:'';
	$E_LINK=$pars->E_LINK?$pars->E_LINK:'';
	$E_TEL=$pars->E_TEL?$pars->E_TEL:'';
	try  {
		if(empty($IDNO)){
			throw new Exception("运单号不存在");
		}
		if(empty($BOX_NO)){
			throw new Exception("请输入集装箱信息");
		}
		$a_member=&m("member");
		//$member=$a_member->get($UID);
		$member=$a_member->get("vhcCode='".$vhcCode."'");
		if(empty($member)===false){
			$UID=$member['user_id'];
			$channelId=$member['channelId'];
			$vhcCode=$member['vhcCode'];
			$driver=$member['real_name'];
			$drivertel=$member['phone_tel'];
		}else
		$UID=0;

		$waybill=&m('waybill');
		$has=$waybill->get("wm_user='".$pars->uid."' and wm_vhc_code='".$vhcCode."' and wm_stauts!='已完成' and wm_stauts!='已取消' and wm_accepted=1");
		if($has)
		{
			throw new Exception("当前车辆还有未完成的运单");
		}


		$goodstrunk=&m('goodstrunk');
		$goods_trunk_sub=&m('goodstrunksub');
		$waybilltrunk=&m('waybilltrunk');

		//回写集装箱号
		$wm_ctnno = $SR_NO ;
		/*foreach($BOX as $K=>$v){
			$SR_NO =$v->SR_NO?$v->SR_NO:'';
			if(!empty($SR_NO)){
			$wm_ctnno.=$SR_NO.'|';
			}
			}*/

		//写入运单主表
		$data_main=array('wm_stauts'=>'已派',
				'wm_type'=>$YWLB,
				'wm_code'=>$IDNO,
				'wm_trailer'=>$wm_trailer,
				'wm_loading_place'=>$B_ADD,
	        	'wm_loading_place'=>$B_ADD,
				'wm_loading_date'=>gmstr2time($B_JH_DD),//date('Y-m-d H:i',),
				'wm_unloading_place'=>$E_ADD,
				'wm_optid'=>$optid,
				'wm_opdate'=>$opDate,
				'wm_ship'=>$SHIP,
				'wm_voyage'=>$SHIP,
				'wm_awb_code'=>$TD_NO,
				'wm_user'=>$UID,
				'wm_carrier_id'=>$carrier_id,
				'wm_carrier'=>$carrier,
				'wm_vhc_code'=>$vhcCode,
				'wm_driver'=>$driver,
				'wm_driver_tel'=>$drivertel,
				'wm_dispatch_date'=>gmtime(),
				'wm_dispatch_person'=>$LINK,
				'wm_dispatch_person_tel'=>$TEL,
				'wm_ctnno'=>$wm_ctnno
		);

		$bill_id = $waybill->add($data_main);

		//写入货物
		$data_goods=array(
			'g_type'=>$YWLB,
			'g_outkey'=>$SR_NO,
			'g_awb_code'=>$TD_NO,
			'g_ship'=>$SHIP,	
			'g_status'=>'已派',
			'g_voyage'=>$OVOY,
			'g_optid'=>$optid,
			'g_opdate'=>$opDate,
			'g_collectiontime'=>gmstr2time($E_JH_DD) ,//date('Y-m-d H:i',),
			'g_packingtime'=>gmstr2time($B_JH_DD),//date('Y-m-d H:i',),
			'g_container_depot'=>$B_ADD,
			'g_container_man'=>$B_LINK,
			'g_container_tel'=>$B_TEL,
			'g_full_container_depot'=>$E_ADD,
			'g_full_container_man'=>$E_LINK,
			'g_full_container_tel'=>$E_TEL,
			'g_loading_place'=>$B_ADD,
			'g_loading_man'=>$B_LINK,
			'g_loading_tel'=>$B_TEL,
		);
		$gid=$goodstrunk->add($data_goods);

		//写入箱型箱量
		$data_goods_sub=array('g_ctn_no'=>$BOX_NO,'gs_gtid'=>$gid,'g_box'=>$CX,'g_volume'=>$QTY,'g_outkey'=>$SR_NO,'g_itm'=>$ITM);
		$gsid=$goods_trunk_sub->add($data_goods_sub);
		$waybilltrunk->add(array('ws_wmtid'=>$bill_id,'ws_gid'=>$gid,'ws_gstid'=>$gsid,'ws_volume'=>$QTY));
			
		//TODO: 添加运程
		addhauldeploy(4,$bill_id,'集港',true,null,null,null,null);

		$status=1;
		// $rnt=array("wm_tid"=>$bill_id);
        $rnt = $waybill->get($bill_id);


		$pars->tid=$bill_id;
		$pars->type=4;
		waybillsubmit($pars);
	}
	catch (Exception $exp){
		$rnt=$exp->getMessage();
	}
	return JSONResult($status,$rnt,$pars);
}


function autocode(){
	$db=&db();
	$code='';
	$sql="select * from zys_dictionary where d_code='wm_code'";
	$gz=$db->getRow($sql);
	if($gz){
		$code.=$gz['d_assist'];
		$code.=($gz['d_value']+1);
	}
	$sql="select 1 from zys_waybill_main where wm_code='".$code."'";
	$way=$db->getOne($sql);
	if($way){
		$this->autocode();
	}
	$sql="UPDATE zys_dictionary SET d_value=d_value+1 WHERE d_code='wm_code'";
	$db->query($sql);

	return $code;
}

/**
 * 车号登记 mxb 0531
 * @param unknown_type $pars
 * @throws Exception
 */
function pt_plateadd($pars){
	$status=0;
	$plate=$pars->plate?$pars->plate:'';
	try{
		if(empty($plate)){
			throw new Exception('车号无效');
		}
		$waybill=&m('waybill');
		$sql="exec pt_plateadd '".$plate."'";
		$bill=$waybill->sqldb->getRow($sql);

		if($bill['flag']=='F'){
			throw new Exception($bill['ts']);
		}
		$list="操作成功";
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 查当前拖板 mxb 0531
 * @param unknown_type $pars
 * @throws Exception
 */
function pt_palletcheckQ($pars){
	$status=0;
	$plate=$pars->plate?$pars->plate:'';
	try{
		if(empty($plate)){
			throw new Exception('车号无效');
		}
//		$waybill=&m('waybill');
//		$sql="exec pt_palletcheck 'Q','".$plate."','',''";
//		$bill=$waybill->sqldb->getRowp($sql);

		$list=$bill['ts'];
		if(empty($list)){
			$list="";
		}
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 挂拖板 mxb 0531
 * @param unknown_type $pars
 * @throws Exception
 */
function pt_palletcheckB($pars){
	$status=0;
	$plate=$pars->plate?$pars->plate:'';
	$pallet=$pars->pallet?$pars->pallet:'';
	try{
		if(empty($plate)){
			throw new Exception('车号无效');
		}
		if(empty($pallet)){
			throw new Exception('拖板号无效');
		}
		$waybill=&m('waybill');
		$sql="exec pt_palletcheck 'B','".$plate."','".$pallet."',''";
		$bill=$waybill->sqldb->getRowp($sql);

		if($bill['flag']=='F'){
			throw new Exception($bill['ts']);
		}
		$list="操作成功";
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 解拖板 mxb 0531
 * @param unknown_type $pars
 * @throws Exception
 */
function pt_palletcheckD($pars){
	$status=0;
	$plate=$pars->plate?$pars->plate:'';
	try{
		if(empty($plate)){
			throw new Exception('车号无效');
		}
		$waybill=&m('waybill');
		$sql="exec pt_palletcheck 'D','".$plate."','',''";
		$bill=$waybill->sqldb->getRowp($sql);

		if($bill['flag']=='F'){
			throw new Exception($bill['ts']);
		}
		$list="操作成功";
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

function upamin($pars){
	$status=0;
	$db=&db();
	$wm_code = empty($pars->wm_code) ? '' : $pars->wm_code;
	$AMTN=!empty($pars->AMTN) ? floatval($pars->AMTN) : 0;
	try{
		$sql = "select * from zys_waybill_main where wm_code='" . $wm_code . "'";
		$old = $db->getRow($sql);

		if (empty($old)) {
			throw new Exception("运单号不存在");
		}

		if ($old['wm_stauts'] != '已派' || !empty($old['wm_user']) || !empty($old['wm_driver'])|| !empty($old['wm_vhc_code'])) {
			throw new Exception("运单已经不能修改");
		}

		$sql="update zys_waybill_main set AMTN='".$AMTN."' where wm_code='" . $wm_code . "'";
		$db->query($sql);

		$list="操作成功";
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 创建运单
 * @param unknown_type $pars
 * @throws Exception
 */
function createwaybillinout($pars)
{
	$status = 0;
	$g_tid = 0;
	$wm_tid = 0;
	try {
		$db =& db();
		$g_optid = 0;
		$g_ownertid = 0;
        $g_qrcode = !empty($pars->g_qrcode) ? trim($pars->g_qrcode) : '';
        $g_op = !empty($pars->g_op) ? trim($pars->g_op) : '';
		$g_owner = !empty($pars->g_owner) ? trim($pars->g_owner) : '';
		$g_owner_tel = !empty($pars->g_owner_tel) ? trim($pars->g_owner_tel) : '';
		$g_type = !empty($pars->g_type) ? $pars->g_type : '';
		$g_ship = !empty($pars->g_ship) ? $pars->g_ship : '';
		$g_voyage = !empty($pars->g_voyage) ? $pars->g_voyage : '';
		$g_awb_code = !empty($pars->g_awb_code) ? $pars->g_awb_code : '';

		$g_packingtime = empty($pars->g_packingtime) ? '' : gmstr2time($pars->g_packingtime);//出口为装箱时间，进口为送达时间
		$g_collectiontime = empty($pars->g_collectiontime) ? '' : gmstr2time($pars->g_collectiontime);//出口为集港时间，进口为背箱时间

		$g_container_depot = !empty($pars->g_container_depot) ? trim($pars->g_container_depot) : '';
		$g_container_lng = !empty($pars->g_container_lng) ? floatval($pars->g_container_lng) : 0;
		$g_container_lat = !empty($pars->g_container_lat) ? floatval($pars->g_container_lat) : 0;
		$g_full_container_depot = !empty($pars->g_full_container_depot) ? trim($pars->g_full_container_depot) : '';
		$g_full_container_lng = !empty($pars->g_full_container_lng) ? floatval($pars->g_full_container_lng) : 0;
		$g_full_container_lat = !empty($pars->g_full_container_lat) ? floatval($pars->g_full_container_lat) : 0;
		$g_loading_place = !empty($pars->g_loading_place) ? trim($pars->g_loading_place) : '';
		$g_loading_lng = !empty($pars->g_loading_lng) ? floatval($pars->g_loading_lng) : 0;
		$g_loading_lat = !empty($pars->g_loading_lat) ? floatval($pars->g_loading_lat) : 0;

		$g_loading_man = !empty($pars->g_loading_man) ? trim($pars->g_loading_man) : '';
		$g_loading_tel = !empty($pars->g_loading_tel) ? trim($pars->g_loading_tel) : '';
		$g_container_man = !empty($pars->g_container_man) ? trim($pars->g_container_man) : '';
		$g_container_tel = !empty($pars->g_container_tel) ? trim($pars->g_container_tel) : '';
		$g_full_container_man = !empty($pars->g_full_container_man) ? trim($pars->g_full_container_man) : '';
		$g_full_container_tel = !empty($pars->g_full_container_tel) ? trim($pars->g_full_container_tel) : '';

		$g_note = empty($pars->g_note) ? '' : trim($pars->g_note);
		$wm_code = empty($pars->wm_code) ? '' : $pars->wm_code; // 运单号
		$wm_ctnno= empty($pars->SR_NO) ? '' : $pars->SR_NO;
		$g_itm= empty($pars->ITM) ? '' : $pars->ITM;
		$wm_requiredl_note = !empty($pars->wm_requiredl_note) ? trim($pars->wm_requiredl_note) : '';
		$AMTN=!empty($pars->AMTN) ? floatval($pars->AMTN) : 0;


		$g_sub = !empty($pars->g_sub) ? $pars->g_sub : '';

		if (empty ($g_sub)) {
			//throw new Exception ('集装箱信息不能为空');
		}

		$g_sub = json_decode(json_encode($g_sub), true);
		if (empty ($g_sub)) {
			//throw new Exception ('集装箱信息错误');
		}

		if ($g_type == '集卡疏港业务'||$g_type == '集卡空箱') {
			$g_typet="疏港";
		}

		if ($g_type == '集卡重箱'||$g_type == '集卡门点业务') {
			$g_typet="集港";
		}

		if (empty($wm_code)) {
			throw new Exception("运单号不能为空");
		}

		$wm_op = !empty($pars->wm_op) ? trim($pars->wm_op) : '';
		$member_mod=&m("member");
		$operator_mod=&m("operator");
		if(empty($wm_op)){
			throw new Exception("运单创建用户不存在");
		}
		$wm_op_user=$member_mod->get("user_name='$wm_op'");
		if(empty($wm_op_user)){
			throw new Exception("运单用户不存在");
		}
		if ($wm_op_user['del']) {
			throw new Exception("运单用户已经被禁用");
		}
		$wm_optid = $wm_op_user['user_id'];
		$wm_carrier_id=$wm_op_user['unit'];
		if (empty($wm_carrier_id)) {
			//throw new Exception("运单单位不存在");
		}
		$wm_carrierinfo = $operator_mod->get($wm_carrier_id);
		if (empty($wm_carrierinfo)) {
			//throw new Exception("运单单位不存在");
		}
		$wm_carrier=$wm_carrierinfo['o_name'];
		if (empty($g_op)) {
			//throw new Exception("货主用户不存在");
		}
		$user=$member_mod->get("user_name='$g_op'");
		if (empty($user)) {
			//throw new Exception("货主用户不存在");
		}
		if ($user['del']) {
			//throw new Exception("货主用户已经被禁用");
		}
		$g_optid = $user['user_id'];
		$g_ownertid=$user['unit'];
		if (empty($g_ownertid)) {
			//throw new Exception("货主单位不存在");
		}
		$g_ownerinfo = $operator_mod->get($g_ownertid);
		if (empty($g_ownerinfo)) {
			//throw new Exception("货主单位不存在");
		}
		$g_owner=$g_ownerinfo['o_name'];

		$wm_vhc_code = empty($pars->wm_vhc_code) ? '' : trim($pars->wm_vhc_code);
		$wm_driver = empty($pars->wm_driver) ? '' : trim($pars->wm_driver);
		$wm_driver_tel = empty($pars->wm_driver_tel) ? '' : trim($pars->wm_driver_tel);
		if (empty($wm_vhc_code)) {
			//throw new Exception("车牌号不能为空");
		}
		if (empty($wm_driver)) {
			//throw new Exception("司机不存在");
		}

		if (empty($vehicle)) {
			//throw new Exception("车辆不存在");
		}

		if($wm_vhc_code){
			$sql = "select * from zys_member m where vhcCode='" . $wm_vhc_code . "' and IFNULL(del,0)!=1";
			$driver = $db->getRow($sql);
			if (empty($driver)) {
				throw new Exception("司机不存在");
			}

			$wm_driver=$driver['user_name'];
			$wm_driver_tel=$driver['user_name'];
		}else{
			$wm_driver='';
			$wm_driver_tel='';
		}

		$sql = "SELECT 1 FROM zys_authoperator WHERE zao_usertid='" . $driver['user_id'] . "' AND zao_authed=1 and zao_otid=" . $wm_carrier_id;
		$dauth = $db->getOne($sql);
		if (empty($dauth)) {
			//throw new Exception("不是您的认证司机");
		}

		if (empty($g_owner_tel)) {
			//throw new Exception("货主电话不能为空");
		}

		if (empty($g_ship)) {
			//throw new Exception("g_ship不能为空");
		}

		if (empty($g_voyage)) {
			//throw new Exception("g_voyage不能为空");
		}

		if (empty($g_awb_code)) {
			//throw new Exception("g_awb_code不能为空");
		}

		if (empty($g_packingtime)) {
			//throw new Exception("g_packingtime不能为空");
		}

		if (empty($g_collectiontime)) {
			//throw new Exception("时间不能为空");
		}

		if (empty($g_container_depot)) {
			//throw new Exception("g_container_depot不能为空");
		}

		if (empty($g_full_container_depot)) {
			throw new Exception("终点不能为空");
		}

		if (empty($g_loading_place)) {
			throw new Exception("起点不能为空");
		}

		if (empty($g_loading_man)) {
			//throw new Exception("g_loading_man不能为空");
		}

		if (empty($g_loading_tel)) {
			//throw new Exception("g_loading_tel不能为空");
		}

		if (empty($g_container_man)) {
			//throw new Exception("g_container_man不能为空");
		}

		if (empty($g_container_tel)) {
			//throw new Exception("g_container_tel不能为空");
		}

		if (empty($g_full_container_man)) {
			//throw new Exception("g_full_container_man不能为空");
		}

		if (empty($g_full_container_tel)) {
			//throw new Exception("g_full_container_tel不能为空");
		}

		$wm_stauts = '已派';
		$wm_accepted = 0;
		$wm_accepted_time = 0;
		$sql = "select * from zys_waybill_main where wm_code='" . $wm_code . "'";
		$old = $db->getRow($sql);
		if ($old) {
			if ($g_optid != $old['wm_optid']) {
				throw new Exception("运单号已经存在");
			}

			if ($old['wm_stauts'] != '新建' && $old['wm_stauts'] != '已派' && $old['wm_stauts'] != '已接单') {
				throw new Exception("运单已经存在并且不能修改");
			}

			if ($old['wm_stauts'] == '已接单' && $wm_vhc_code = $old['wm_vhc_code'] && $wm_driver = $old['wm_driver']) {
				$wm_stauts = '已接单';
				$wm_accepted = 1;
				$wm_accepted_time = $old['wm_accepted_time'];
			}
		}

		//判断监控方案
		$zmm_tid = !empty($pars->zmm_tid) ? intval($pars->zmm_tid) : 0;
		$sql = "select 1 from zys_monitor_main where zmm_otid='" . $wm_carrier_id . "' and zmm_tid='" . $zmm_tid . "'";
		$zmm = $db->getOne($sql);
		if (empty($zmm)) {
			$zmm_tid = 0;
		}


	 //写货单
		$sql = "insert into zys_goods_trunk set g_type='" . $g_type . "',g_status='已派',g_code='T" . gmtime() . "',
		g_ship='" . $g_ship . "',g_voyage='" . $g_voyage . "',g_awb_code='" . $g_awb_code . "',
		g_packingtime='" . $g_packingtime . "',g_collectiontime='" . $g_collectiontime . "',
		g_container_depot='" . $g_loading_place . "',g_full_container_depot='" . $g_full_container_depot . "',g_loading_place='" . $g_loading_place . "',
 g_container_man='" . $g_container_man . "',g_container_tel='" . $g_container_tel . "',
 g_optid='" . $g_optid . "',g_opname='" . $g_op . "',g_opdate='" . gmtime() . "'";

		$db->query($sql);
		$g_tid = $db->insert_id();
		if (empty($g_tid)) {
			throw new Exception("操作失败请重试");
		}

		if($g_sub){
			foreach ($g_sub as $v) {
				$g_box = $v['g_box'];
				$g_volume = $v['g_volume'];

				$g_ctn_no = $v['g_ctn_no'];
				if (empty($g_box)) {
					throw new Exception('g_sub中g_box不能为空');
				}
				if (empty($g_volume)) {
					throw new Exception('g_sub中g_volume不能为空');
				}

				//写货单明细
				$sql = "insert into zys_goods_trunk_sub set gs_gtid='" . $g_tid . "',
		g_box='" . $g_box . "' ,g_volume='" . $g_volume . "',g_volumep='" . $g_volume . "',g_ctn_no ='" . $g_ctn_no . "'
		,g_outkey='".$wm_ctnno."',g_itm='".$g_itm."'";

				$db->query($sql);
				$gs_tid = $db->insert_id();
				if (empty($gs_tid)) {
					throw new Exception("操作失败请重试");
				}
			}
		}

		$wm_loading_place   = $g_loading_place;
		$wm_unloading_place = $g_full_container_depot;

		$sql = "insert into zys_waybill_main set wm_stauts='" . $wm_stauts . "',wm_type='" . $g_type . "',wm_code='" . $wm_code . "',wm_accepted='" . $wm_accepted . "',wm_accepted_time='" . $wm_accepted_time . "',wm_optid='" . $wm_optid . "',wm_opdate='" . gmtime() . "',
		wm_user='" . $driver['user_id'] . "',wm_vhc_code='" . $wm_vhc_code . "',wm_driver='" . $driver['user_name'] . "',wm_driver_tel='" . $wm_driver_tel . "',wm_carrier='" . $wm_carrier . "',wm_carrier_id='" . $wm_carrier_id . "',
		wm_uuid='" . $vehicle['uuid'] . "',wm_dispatch_date='" . gmtime() . "',wm_dispatch_person='" . $user['user_name'] . "',wm_dispatch_person_tel='" . $user['phone_mob'] . "'
		,wm_requiredl_note='" . $wm_requiredl_note . "',wm_zmmtid='" . $zmm_tid . "',wm_loading_place='".$wm_loading_place."',wm_unloading_place='".$wm_unloading_place.
      "',wm_loading_date='". $g_packingtime. "',wm_ship='". $g_ship."', wm_note='". $g_note."', wm_voyage='". $g_voyage."',wm_awb_code='". $g_awb_code."',wm_ctnno='". $wm_ctnno."',wm_qrcode='". $g_qrcode."',AMTN='".$AMTN."'";

		$db->query($sql);
		$wm_tid = $db->insert_id();
		if (empty($wm_tid)) {
			throw new Exception("操作失败请重试");
		}

        $sql = "select * from zys_goods_trunk_sub where gs_gtid='" . $g_tid . "'";
		$trunk_sub = $db->getAll($sql);
		if (empty($trunk_sub)) {
			//throw new Exception("操作失败请重试");
		}

		if($trunk_sub){
			foreach ($trunk_sub as $v) {
				//写运单明细
				$sql = "insert into zys_waybill_sub_trunk set ws_gid='" . $g_tid . "',ws_gstid='" . $v['gs_tid'] . "',ws_wmtid='" . $wm_tid . "',
		ws_volume='" . $v['g_volume'] . "',ws_new=1";
				$db->query($sql);
				$ws_tid = $db->insert_id();
				if (empty($ws_tid)) {
					//throw new Exception("操作失败请重试");
				}
			}
		}

		//写进程
		$zhdm_tid = !empty($pars->zhdm_tid) ? intval($pars->zhdm_tid) : 0;
		if ($zhdm_tid) {
			$sql = "select * from zys_haul_define_main where zhdm_type='" . $g_typet . "' and zhdm_otid='" . $wm_carrier_id . "' and zhdm_tid=" . $zhdm_tid;
			$haul = $db->getRow($sql);

			if ($haul) {
				$sql = "SELECT * FROM zys_haul_define WHERE h_zhdmtid='" . $zhdm_tid . "'";
				$temp = $db->getAll($sql);

				if ($temp) {
					$haul_mod =& m('haul');
					foreach ($temp as $v) {
						$data['h_wmtid'] = $wm_tid;
						$data['h_name'] = $v['h_name'];
						$data['h_short_name'] = $v['h_short_name'];

						$data['h_order'] = $v['h_order'];
						if ($g_typet == '疏港') {
							if ($v['h_linkman'] == '@TI_linkman' || $v['h_linkman'] == '@TI_container_man' || $v['h_linkman'] == '@TI_full_container_man' || $v['h_linkman_tel'] == '@TI_tel' ||
							$v['h_linkman_tel'] == '@TI_container_tel' || $v['h_linkman_tel'] == '@TI_full_container_tel' || $v['h_address'] == '@TI_unload' || $v['h_address'] == '@TI_container_depot' || $v['h_address'] == '@TI_full_container_depot' || $v['h_date'] == '@TI_unload_time' || $v['h_date'] == '@TI_collect_time'
							) {
								//查数据库
								$sql = "select gt.g_container_man,gt.g_container_tel,gt.g_container_depot,g_container_lng,g_container_lat,gt.g_full_container_man,gt.g_full_container_tel,gt.g_full_container_depot,g_full_container_lng,g_full_container_lat,gt.g_loading_place,gt.g_loading_lng,gt.g_loading_lat,gt.g_loading_man,gt.g_loading_tel,gt.g_packingtime,gt.g_collectiontime from zys_goods_trunk as gt left join zys_waybill_sub_trunk as wst on gt.g_tid= wst.ws_gid where wst.ws_wmtid=" . $wm_tid . " GROUP BY ws_gid";
								$row = $db->getrow($sql);
								if ($v['h_linkman'] == '@TI_linkman') {
									$data['h_linkman'] = $row['g_loading_man'];
								} elseif ($v['h_linkman'] == '@TI_container_man') {

									$data['h_linkman'] = $row['g_container_man'];
								} elseif ($v['h_linkman'] == '@TI_full_container_man') {

									$data['h_linkman'] = $row['g_full_container_man'];
								} else {
									$data['h_linkman'] = $v['h_linkman'];
								}

								if ($v['h_linkman_tel'] == '@TI_tel') {

									$data['h_linkman_tel'] = $row['g_loading_tel'];

								} elseif ($v['h_linkman_tel'] == '@TI_container_tel') {

									$data['h_linkman_tel'] = $row['g_container_tel'];

								} elseif ($v['h_linkman_tel'] == '@TI_full_container_tel') {

									$data['h_linkman_tel'] = $row['g_full_container_tel'];
								} else {

									$data['h_linkman_tel'] = $v['h_linkman_tel'];
								}

								if ($v['h_address'] == '@TI_unload') {
									$data['h_address'] = $row['g_loading_place'];
									$data['h_lng'] = $row['g_loading_lng'];
									$data['h_lat'] = $row['g_loading_lat'];
								} elseif ($v['h_address'] == '@TI_container_depot') {
									$data['h_address'] = $row['g_container_depot'];
									$data['h_lng'] = $row['g_container_lng'];
									$data['h_lat'] = $row['g_container_lat'];
								} elseif ($v['h_address'] == '@TI_full_container_depot') {
									$data['h_address'] = $row['g_full_container_depot'];
									$data['h_lng'] = $row['g_full_container_lng'];
									$data['h_lat'] = $row['g_full_container_lat'];
								} else {
									$data['h_address'] = $v['h_address'];
								}
								if ($v['h_date'] == '@TI_unload_time') {
									$data['h_required_service_date'] = $row['g_packingtime'];
								} elseif ($v['h_date'] == '@TI_collect_time') {
									$data['h_required_service_date'] = $row['g_collectiontime'];
								} else {
									$data['h_required_service_date'] = $v['h_date'];
								}
							} else {
								$data['h_linkman'] = $v['h_linkman'];
								$data['h_linkman_tel'] = $v['h_linkman_tel'];
								$data['h_address'] = $v['h_address'];
								$data['h_required_service_date'] = $v['h_date'];
							}
						} elseif ($g_typet == '集港') {
							if ($v['h_linkman'] == '@TE_linkman' || $v['h_linkman'] == '@TE_container_man' || $v['h_linkman'] == '@TE_full_container_man' || $v['h_linkman_tel'] == '@TE_tel' || $v['h_linkman_tel'] == '@TE_container_tel' || $v['h_linkman_tel'] == '@TE_full_container_tel' ||
							$v['h_address'] == '@TE_load' || $v['h_address'] == '@TE_container_depot' || $v['h_address'] == '@TE_full_container_depot' || $v['h_date'] == '@TE_load_tine' || $v['h_date'] == '@TE_collect_time'
							) {
								//查数据库
								$sql = "select gt.g_container_man,gt.g_container_tel,gt.g_container_depot,g_container_lng,g_container_lat,gt.g_full_container_man,gt.g_full_container_tel,gt.g_full_container_depot,g_full_container_lng,g_full_container_lat,gt.g_loading_place,gt.g_loading_lng,gt.g_loading_lat,gt.g_loading_man,gt.g_loading_tel,gt.g_packingtime,gt.g_collectiontime from zys_goods_trunk as gt left join zys_waybill_sub_trunk as wst on gt.g_tid= wst.ws_gid where wst.ws_wmtid=" . $wm_tid . " GROUP BY ws_gid";
								$row = $db->getrow($sql);
								if ($v['h_linkman'] == '@TE_linkman') {
									$data['h_linkman'] = $row['g_loading_man'];
								} elseif ($v['h_linkman'] == '@TE_container_man') {

									$data['h_linkman'] = $row['g_container_man'];
								} elseif ($v['h_linkman'] == '@TE_full_container_man') {

									$data['h_linkman'] = $row['g_full_container_man'];
								} else {
									$data['h_linkman'] = $v['h_linkman'];
								}
								if ($v['h_linkman_tel'] == '@TE_tel') {
									$data['h_linkman_tel'] = $row['g_loading_tel'];
								} elseif ($v['h_linkman_tel'] == '@TE_container_tel') {

									$data['h_linkman_tel'] = $row['g_container_tel'];

								} elseif ($v['h_linkman_tel'] == '@TE_full_container_tel') {

									$data['h_linkman_tel'] = $row['g_full_container_tel'];
								} else {
									$data['h_linkman_tel'] = $v['h_linkman_tel'];
								}
								if ($v['h_address'] == '@TE_load') {
									$data['h_address'] = $row['g_loading_place'];
									$data['h_lng'] = $row['g_loading_lng'];
									$data['h_lat'] = $row['g_loading_lat'];
								} elseif ($v['h_address'] == '@TE_container_depot') {
									$data['h_address'] = $row['g_container_depot'];
									$data['h_lng'] = $row['g_container_lng'];
									$data['h_lat'] = $row['g_container_lat'];
								} elseif ($v['h_address'] == '@TE_full_container_depot') {
									$data['h_address'] = $row['g_full_container_depot'];
									$data['h_lng'] = $row['g_full_container_lng'];
									$data['h_lat'] = $row['g_full_container_lat'];
								} else {
									$data['h_address'] = $v['h_address'];
								}
								if ($v['h_date'] == '@TE_load_tine') {
									$data['h_required_service_date'] = $row['g_packingtime'];
								} elseif ($v['h_date'] == '@TE_collect_time') {
									$data['h_required_service_date'] = $row['g_collectiontime'];
								} else {
									$data['h_required_service_date'] = $v['h_date'];
								}
							} else {
								$data['h_linkman'] = $v['h_linkman'];
								$data['h_linkman_tel'] = $v['h_linkman_tel'];
								$data['h_address'] = $v['h_address'];
								$data['h_required_service_date'] = $v['h_date'];
							}
						}

						$data['h_changecolor'] = $v['h_changecolor'];
						//$data['h_sign'] = $v['h_sign'];
						//$data['h_transfer'] = $v['h_transfer'];
						//$data['h_multi_unload'] = $v['h_multi_unload'];
						$data['h_note']=$v['h_note'];
						$data['h_exception'] = $v['h_exception'];
						$data['h_exceptionhour'] = $v['h_exceptionhour'];
						$data['h_type'] = $v['h_type'];
						$data['h_range'] = intval($v['h_range']);
						$id = $haul_mod->add($data);

						$sql = "select * from zys_haul_define_collect where hc_h_tid=" . $v['h_tid'];
						$collect = $db->getAll($sql);
						if ($collect) {
							foreach ($collect as $c) {
								$sql = "insert into zys_haul_collect set hc_h_tid='" . $id . "',
						h_collect_type='" . $c['h_collect_type'] . "',h_collect_des='" . $c['h_collect_des'] . "'";
								$db->query($sql);
							}
						}
					}

				}
			}
		}

		$waybill_mod =& m('waybill');
		$waybill_info=$waybill_mod->get($wm_tid);
		//发送推送消息
		$waybill_mod->pushmessage($waybill_info);
		/**
		 *  处理运单
		 */
		//$waybill_mod->processwaybill($waybill_info);
		if ($old) {
			$sql = "delete from zys_goods_trunk where
			exists(select 1 from zys_waybill_sub_trunk where ws_gid=g_tid and ws_wmtid='" . $old['wm_tid'] . "')";
			$db->query($sql);

			$sql = "delete from zys_goods_trunk_sub where
			exists(select 1 from zys_waybill_sub_trunk where ws_gstid=gs_tid and ws_wmtid='" . $old['wm_tid'] . "')";
			$db->query($sql);

			$sql = "delete from zys_waybill_main where wm_tid='" . $old['wm_tid'] . "'";
			$db->query($sql);

			$sql = "delete from zys_waybill_sub_trunk where ws_wmtid='" . $old['wm_tid'] . "'";
			$db->query($sql);
		}

//		if ($wm_driver&&$wm_driver_tel&&checkUrl(SOAP_URL)) {
//			$client = new SoapClient(SOAP_URL);
//
//			$param = array();
//			$param['Code'] = $wm_code;
//			$param['CarNo'] = $wm_vhc_code;
//			$param['Driver'] = $wm_driver;
//			$param['Tel'] = $wm_driver_tel;
//			$response = $client->__soapCall("ReturnCarNo", array($param));
//			$response = json_decode($response->ReturnCarNoResult, true);
//		}

		$status = 1;
		$rnt = '操作成功';
	} catch (Exception $exp) {
		put_log($exp->getMessage(), json_encode($pars), json_encode(debug_backtrace()), (__LINE__));
		$rnt = $exp->getMessage();
		if ($g_tid) {
			$sql = "delete from zys_goods_trunk where g_tid=" . $g_tid;
			$db->query($sql);

			$sql = "delete from zys_goods_trunk_sub where gs_gtid=" . $g_tid;
			$db->query($sql);
		}

		if ($wm_tid) {
			$sql = "delete from zys_waybill_main where wm_tid=" . $wm_tid;
			$db->query($sql);

			$sql = "delete from zys_waybill_sub_trunk where ws_wmtid=" . $wm_tid;
			$db->query($sql);
		}
	}
	return JSONResult($status, $rnt, $pars);
}

function dropwaybill($pars)
{
	$status = 0;
	$g_tid = 0;
	$wm_tid = 0;
	try {
		$db =& db();
		$g_optid = 0;
		$g_ownertid = 0;
		$g_op = !empty($pars->g_op) ? trim($pars->g_op) : '';
		$g_owner = !empty($pars->g_owner) ? trim($pars->g_owner) : '';
		$wm_code = empty($pars->wm_code) ? '' : $pars->wm_code;

		if (empty($wm_code)) {
			throw new Exception("运单不存在");
		}

		if (empty($g_owner)) {
			//throw new Exception("货主单位不存在");
		}

		$sql = "select o_tid from zys_operator where o_name='" . $g_owner . "'";
		$g_ownertid = $db->getOne($sql);
		if (empty($g_ownertid)) {
			//throw new Exception("单位不存在");
		}

		if (empty($g_op)) {
			throw new Exception("用户不存在");
		}
		$sql = "select * from zys_member where user_name='" . $g_op . "'";
		$user = $db->getRow($sql);
		if (empty($user)) {
			throw new Exception("用户不存在");
		}

		$g_optid = $user['user_id'];
		if ($user['del']) {
			throw new Exception("用户已经被禁用");
		}

		$sql = "select * from zys_waybill_main where wm_code='" . $wm_code . "' and wm_optid='" . $g_optid . "'";
		$old = $db->getRow($sql);

		if (!$old) {
			throw new Exception("运单不存在");
		}

		if ($old['wm_stauts'] != '新建' && $old['wm_stauts'] != '已派' && $old['wm_stauts'] != '已接单' && $old['wm_stauts'] != '已取消') {
			throw new Exception("运单已经发出不能修改");
		}
		if($old['wm_type']=="疏港"||$old['wm_type']=="集港"){
			$sql = "delete from zys_goods_trunk where
			exists(select 1 from zys_waybill_sub_trunk where ws_gid=g_tid and ws_wmtid='" . $old['wm_tid'] . "')";
			$db->query($sql);

			$sql = "delete from zys_goods_trunk_sub where
			exists(select 1 from zys_waybill_sub_trunk where ws_gstid=gs_tid and ws_wmtid='" . $old['wm_tid'] . "')";
			$db->query($sql);

			$sql = "delete from zys_waybill_sub_trunk where ws_wmtid='" . $old['wm_tid'] . "'";
			$db->query($sql);
		}
		else {
			$sql = "delete from zys_goods_normal where
			exists(select 1 from zys_waybill_sub_normal where ws_gid=g_tid and ws_wmtid='" . $old['wm_tid'] . "')";
			$db->query($sql);

			$sql = "delete from zys_goods_normal_sub where
			exists(select 1 from zys_waybill_sub_normal where ws_gstid=gs_tid and ws_wmtid='" . $old['wm_tid'] . "')";
			$db->query($sql);

			$sql = "delete from zys_waybill_sub_normal where ws_wmtid='" . $old['wm_tid'] . "'";
			$db->query($sql);
		}

		$sql = "delete from zys_waybill_main where wm_tid='" . $old['wm_tid'] . "'";
		$db->query($sql);

		$sql = "delete from zys_haul where h_wmtid='" . $old['wm_tid'] . "'";
		$db->query($sql);


		$status = 1;
		$rnt = '操作成功';
	} catch (Exception $exp) {
		//put_log($exp->getMessage(), json_encode($pars), json_encode(debug_backtrace()), (__LINE__));
		$rnt = $exp->getMessage();
	}
	return JSONResult($status, $rnt, $pars);
}

/**
 * 强制完成
 * @param unknown_type $pars
 */
function finishwaybill($pars)
{
	$status = 0;
	$db =&db();
	try {
		$g_op = !empty($pars->g_op) ? trim($pars->g_op) : '';
		$wm_code = empty($pars->wm_code) ? '' : $pars->wm_code;

		if (empty($wm_code)) {
			throw new Exception("运单不存在");
		}

		if (empty($g_op)) {
			throw new Exception("用户不存在");
		}

		$sql = "select * from zys_member where user_name='" . $g_op . "'";
		$user = $db->getRow($sql);
		if (empty($user)) {
			throw new Exception("用户不存在");
		}

		$g_optid = $user['user_id'];
		if ($user['del']) {
			throw new Exception("用户已经被禁用");
		}

		$sql = "select * from zys_waybill_main where wm_code='" . $wm_code . "' and wm_optid='" . $g_optid . "'";
		$waybillinfo = $db->getRow($sql);

		if (!$waybillinfo) {
			throw new Exception("运单不存在");
		}

		$a_member=&m("member");
		$data = array('wm_complete' => 1, 'wm_complete_time' => gmtime(), 'wm_stauts' => '已完成');
		$a_member->edit($pars->uid, array('current_waybill' => 0));

		$waybill_mod=&m("waybill");
		$waybill_mod->edit($tid, $data);
		$status = 1;
	} catch (Exception $exp) {
		$list = $exp->getMessage();
	}
	return JSONResult($status, $list, $pars);
}